package com.springboot.wisdom.upload.controller;

import cn.hutool.core.lang.UUID;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.springboot.wisdom.common.common.ResultUtil;
import com.springboot.wisdom.common.common.bean.MyResult;
import com.springboot.wisdom.common.util.SystemOSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description
 * @Author LY L
 * @Date 2024-11-05
 */
@Api(tags = "文件模块")
@ApiSupport(author = "LY L")
@RestController
@RequestMapping(value = "/file", produces = {"application/json;charset=UTF-8"})
@Slf4j
@Validated     // springboot 2.5.* 版本需要在类上标注 @Validated 注解校验注解才会生效。
public class FileController {

    /**
     * 根据当前项目所在的操作系统选择不同的路径。
     */
    private String filePath;
    private String fileWebUrl;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    /**
     * @param prefixesUrl 前缀目录【可选】。格式必须为：xxx/。
     * @param file
     * @return
     */
    /**
     * @param prefixesUrl
     * @param file
     * @param request
     * @return 文件位置。
     */
    @ApiOperation(value = "上传单个文件", notes = "")
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public MyResult<String> upload(
            @RequestParam(defaultValue = "") String prefixesUrl,
            @RequestPart(value = "file") @NotNull(message = "上传的文件不能为空！") MultipartFile file,
            HttpServletRequest request
    ) {

//        filePath = SystemOSUtil.getFilePath();
//
//        System.out.println("filePath    ======>      " + filePath);
//        System.out.println("上传的文件位置    ======>      " + SystemOSUtil.getFilePath());
//        if (ObjectUtils.isEmpty(file) || file.getSize() <= 0) {
//            return ResultUtil.error("文件内容为空！请重新上传！");
//        }
//        try {
//            byte[] bytes = file.getBytes();
//            // 文件名 file.getOriginalFilename()。
//            System.out.println("上传的文件名    ======>      " + file.getOriginalFilename());
//            File uploadedFile = new File(this.filePath + prefixesUrl + file.getOriginalFilename());
//            System.out.println("uploadedFile.getParentFile().exists() = " + uploadedFile.getParentFile().exists());
//            if (!uploadedFile.getParentFile().exists()) {
//                if (!uploadedFile.getParentFile().mkdirs()) {
//                    return ResultUtil.error("服务器异常，请重新上传！");
//                }
//            }
//            file.transferTo(uploadedFile);
//            return ResultUtil.success("文件上传成功！");
//        } catch (Exception e) {
//            // 上传失败！
//            e.printStackTrace();
//            return ResultUtil.error("程序错误，请重新上传！");
//        }


        filePath = SystemOSUtil.getFilePath();
        fileWebUrl = SystemOSUtil.getFileWebUrl();

        System.out.println("filePath = " + filePath);
        System.out.println("fileWebUrl = " + fileWebUrl);

        // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
        // 比如：/2019/06/06/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
        File folder = new File(filePath, format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();

        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

//            System.out.println("request.getScheme() = " + request.getScheme());
//            System.out.println("request.getServerName() = " + request.getServerName());
//            System.out.println("request.getServerPort() = " + request.getServerPort());
//            System.out.println("request.getContextPath() = " + request.getContextPath());

//            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"+format + newName;
            String filePath = fileWebUrl + format + newName;
            return ResultUtil.success(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultUtil.error("程序错误，请重新上传！");
    }

    @ApiOperation(value = "下载单个文件", notes = "")
    @GetMapping("/download")
    public String fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName) {
        File file = new File(filePath + '/' + fileName);
        if (!file.exists()) {
            return "下载文件不存在";
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            log.error("{}", e);
            return "下载失败";
        }
        return "下载成功";
    }
}
